<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model="queryParam.keyword" @input="changeValue" style="margin-bottom:10px" type="text"
          prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" />
        <!-- 树形组件 -->
        <el-tree ref="deptTree" node-key="id" @current-change="selectNode" :data="depts" :props="defaultProps"
          default-expand-all :expand-on-click-node="false" :highlight-current="true" />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :size="30" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="email" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template v-slot="{ row }">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>
              <!-- 确定删除员工弹层 -->
              <el-popconfirm title="确认删除该行数据吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination layout="total,prev, pager, next" :total="total" :current-page="queryParam.page"
            :page-size="queryParam.pageSize" @current-change="changePage" />
        </el-row>
      </div>
    </div>
    <!-- 弹层组件-导入excel -->
    <import-excel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getEmployeeList" />
    <!-- 弹层组件-角色分配 -->
    <el-dialog :visible.sync="showRoleDialog" title="分配角色">
      <!-- 弹层内容 -->
      <!-- checkbox -->
      <el-checkbox-group v-model="roleIds">
        <!-- 放置n个的checkbox  要执行checkbox的存储值 item.id-->
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
        <!-- 确定取消按钮 -->
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnRoleOK">确定</el-button>
          <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartment } from '@/api/department';
import { transListToTreeData } from '@/utils';
import { exportEmployee, getEmployeeList, delEmployee, getEnableRoleList, getEmployeeDetail, assignRole } from '@/api/employee';
import FileSaver from 'file-saver'
import ImportExcel from '@/views/employee/component/import-excel'
export default {
  components: {
    ImportExcel
  },
  name: 'Employee',
  data() {
    return {
      depts: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 存储查询参数，传给接口
      queryParam: {
        departmentId: null,//记录部门id
        page: 1,//设置初始页码
        pageSize: 10,//设置初始每页显示条数
        keyword: ''//搜索关键字,后端接口会根据关键字过滤员工
      },
      total: 0,//总条数
      list: [],//员工数据
      showExcelDialog: false, // 控制excel的弹层显示和隐藏

      showRoleDialog: false, // 用来控制角色弹层的显示
      roleList: [], // 接收角色列表
      roleIds: [],// 用来双向绑定数据的
      currentUserId: null // 用来记录当前点击的用户id
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      this.depts = transListToTreeData(await getDepartment(), 0)
      this.queryParam.departmentId = this.depts[0].id,// 记录首个节点id，
        this.$nextTick(() => {
          this.$refs.deptTree.setCurrentKey(this.queryParam.departmentId)
        }
        )
      this.getEmployeeList()// 初始化时获取员工列表
    },
    selectNode(node) {
      this.queryParam.departmentId = node.id
      this.queryParam.page = 1//切换树枝时从第一页开始
      this.getEmployeeList()// 选择节点时获取员工列表
    },
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParam)
      this.list = rows
      this.total = total
    },
    changePage(newpage) {
      this.queryParam.page = newpage
      this.getEmployeeList()//换页时重新获取员工列表
    },
    changeValue() {
      clearTimeout(this.timer)//防止多次触发
      this.timer = setTimeout(() => {
        this.queryParam.page = 1//输入关键字时从第一页开始
        this.getEmployeeList()//输入关键字时重新获取员工列表
      }, 500)
    },
    // 导出excel
    async exportEmployee() {
      const result = await exportEmployee()
      console.log(result)
      FileSaver.saveAs(result, '员工表.xlsx')
    },
    // 删除员工
    // 删除员工方法
    async confirmDel(id) {
      await delEmployee(id)
      if (this.list.length === 1 && this.queryParams.page > 1) this.queryParams.page--
      this.getEmployeeList()
      this.$message.success('删除员工成功')
    },
    // 点击角色按钮弹出层
    async btnRole(id) {
      console.log('Selected User ID:', id);  // 输出id，确认是否传递正确
      this.roleList = await getEnableRoleList()
      // 记录当前点击的id 因为后边 确定取消要存取给对应的用户
      this.currentUserId = id
      const { roleIds } = await getEmployeeDetail(id)
      this.roleIds = roleIds
      this.showRoleDialog = true // 调整顺序
    },
    // 点击角色的确定
    async btnRoleOK() {
      await assignRole({
        id: this.currentUserId,
        roleIds: this.roleIds
      })
      this.$message.success('分配用户角色成功')
      this.showRoleDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;

  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }

  .right {
    flex: 1;
    padding: 20px;

    .opeate-tools {
      margin: 10px;
    }

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>